package com.vote.www.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 汤伟杰 on 2017/5/8.
 */
public class CommonHttp {
    public static Map<String, Object> send(String uri, String method, Map<String,String> params) throws Exception {
        if(params==null){
            params = new HashMap<String, String>();
        }
        String info = null;
        HttpClient httpclient = new HttpClient();//方法调用
       if("get".equals(method.trim().toLowerCase())){
           GetMethod get = new GetMethod(uri);
           httpclient.executeMethod(get);
           info = new String(get.getResponseBody(),"UTF-8");
           Map<String,Object> map = JSONObject.parseObject(info, Map.class);
           return map;
       }else if("post".equals(method.trim().toLowerCase())){
           PostMethod post = new PostMethod(uri);//接口地址
           post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");//格式转换
           for (Map.Entry<String, String> entry : params.entrySet()) {
               post.addParameter(entry.getKey(), entry.getValue());//接口用户名
           }
           httpclient.executeMethod(post);
           info = new String(post.getResponseBody(),"UTF-8");
           Map<String,Object> map = JSONObject.parseObject(info, Map.class);
           return map;
       }else{
           throw new Exception("请求的method只能是get或者post！");
       }

    }
    public static String sendToJson(String uri, String method, Map<String,String> params) throws Exception {
        Map<String,Object> map = send(uri, method, params);
        return JSONObject.toJSONString(map);
    }

}
